/*
 * Copyright (C) 2010 ST-Ericsson AS
 * Author: Erwan Bracq / erwan.bracq@stericsson.com
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * See the NOTICE file distributed with this work for additional
 * information regarding copyright ownership.
 *
 */

#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <dirent.h>
#include <errno.h>
#include <stdlib.h>

#include "mid.h"
#include "mid_log.h"
#include "mid_error.h"
#include "mid_flash.h"
#include "mid_statemachine.h"

static char* refname;

static int isdir(const char* dirname)
{
	struct stat statdata;
	if (stat(dirname, &statdata) == -1) {
		MLGE("MID: Error to get stat for folder: %s. Error: %s", dirname, strerror(errno));
		return -EMIDFS;
	} else
		return S_ISDIR(statdata.st_mode);
}

int cleanupdirname(struct mid *mid_info)
{
	/* TODO error check */
	/* TODO update mid_info field */
	refname = malloc((strlen(mid_info->config->initial_rdir) + 1) * sizeof(char));
	strncpy(refname, mid_info->config->initial_rdir, strlen(mid_info->config->initial_rdir));
	if (refname[strlen(mid_info->config->initial_rdir) - 1] == '/')
		refname[strlen(mid_info->config->initial_rdir) - 1] = '\0';
	else
		refname[strlen(mid_info->config->initial_rdir)] = '\0';
	return 0;
}

int isdirempty(const char* dirname)
{
	int res = 0;
	struct dirent* dinfo;
	DIR* dir = opendir(dirname);

	if (dir == NULL) return -EMIDFS;
	while((dinfo = readdir(dir)) != NULL) res++;
	closedir(dir);
	if(res == 2)
		return 1;
	else
		return 0;
}

int purgedir(const char* directory)
{
	struct dirent* dinfo;
	DIR* dir = NULL;
	char file[FILE_NAME_SZ];
	char dirname[DIR_NAME_SZ];
	int i = 0;

	strncpy(dirname, directory, strlen(directory));
	if (dirname[strlen(directory) - 1] == '/')
		dirname[strlen(directory) - 1] = '\0';
	else
		dirname[strlen(directory)] = '\0';

	dir = opendir(dirname);
	if (dir == NULL) return -EMIDFS;

	while((dinfo = readdir(dir)) != NULL) {

		if (!((strlen(dinfo->d_name) == 1) && (strncmp(dinfo->d_name, ".", 1) == 0)))
		if (!((strlen(dinfo->d_name) == 2) && (strncmp(dinfo->d_name, "..", 2) == 0))) {

			for (i = 0; i < FILE_NAME_SZ; i++) file[i] = '\0';
			strcat(file, dirname);
			strcat(file, "/");
			strcat(file, dinfo->d_name);
			if (isdir(file))
				purgedir(file);
			else
				remove(file);
				/* TODO take care about symlink. They are not deleted */
		}
	}
	closedir(dir);

	if(strncmp(dirname, refname, strlen(dirname)) != 0)
		rmdir(dirname);
	return 0;
}
